from playwright.sync_api import sync_playwright, expect
import time
import os

def run_playwright_demo():
    print("开始运行Playwright示例...")
    with sync_playwright() as p:
        # 使用Chromium浏览器，添加slow_mo参数使操作更慢，便于观察
        browser = p.chromium.launch(
            headless=False,
            slow_mo=100  # 每个操作之间延迟100毫秒
        )
        page = browser.new_page()
        
        try:
            # 访问百度首页
            print("正在访问百度首页...")
            page.goto("https://www.baidu.com", timeout=60000)
            
            # 等待页面加载完成
            page.wait_for_load_state("load")
            print("页面基本加载完成")
            
            # 等待一下，确保页面完全渲染
            time.sleep(2)
            
            # 使用更可靠的选择器定位搜索框
            print("尝试定位搜索框...")
            # 先尝试通过ID定位，如果失败则使用其他方式
            try:
                # 等待搜索框出现并可交互
                page.wait_for_selector("input[name='wd']", state="visible", timeout=20000)
                search_box = page.locator("input[name='wd']")
                print("已找到搜索框")
                
                # 滚动到搜索框位置
                search_box.scroll_into_view_if_needed()
                time.sleep(1)
                
                # 清空搜索框并输入内容
                search_box.clear()
                search_box.fill("Playwright")
                print("已在搜索框中输入'Playwright'")
                
                # 等待搜索按钮出现并点击
                page.wait_for_selector("input[type='submit']", state="visible", timeout=10000)
                search_button = page.locator("input[type='submit']")
                search_button.click()
                print("已点击搜索按钮")
                
                # 等待搜索结果加载
                page.wait_for_load_state("networkidle")
                print("搜索结果已加载")
                
                # 等待几秒，让用户可以看到结果
                time.sleep(3)
                
                # 截图保存 - 使用绝对路径
                screenshot_path = os.path.join(os.getcwd(), "playwright_search_result.png")
                page.screenshot(path=screenshot_path)
                print(f"已保存截图到: {screenshot_path}")
                
                # 获取搜索结果标题
                title = page.title()
                print(f"页面标题: {title}")
                
            except Exception as inner_e:
                print(f"定位元素时出错: {inner_e}")
                # 无论如何尝试截图，用于调试
                error_screenshot_path = os.path.join(os.getcwd(), "error_screenshot.png")
                page.screenshot(path=error_screenshot_path)
                print(f"已保存错误状态截图到: {error_screenshot_path}")
                
        except Exception as e:
            print(f"发生错误: {e}")
            # 尝试获取页面内容进行调试
            try:
                html_content = page.content()
                print(f"页面HTML长度: {len(html_content)} 字符")
                # 只打印前500个字符用于调试
                print(f"页面HTML前500字符: {html_content[:500]}...")
            except:
                print("无法获取页面内容")
        finally:
            # 等待用户确认后再关闭浏览器
            input("按Enter键关闭浏览器...")
            browser.close()
            print("浏览器已关闭")

if __name__ == "__main__":
    run_playwright_demo()